<template>
    <div class="container">
        <div class="logo">
            <img src="@/assets/images/logo.png" alt="logo">
            <h1>登 录</h1>
        </div>
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field v-model="userName" name="userName" label="用户名" placeholder="用户名"
                    :rules="[{ required: true, message: '请填写用户名' }]" />
                <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
                    :rules="[{ required: true, message: '请填写密码' }]" />
                <van-field v-model="code" name="code" label="验证码" placeholder="验证码"
                    :rules="[{ required: true, message: '请填写验证码' }]" />
                <img :src="codeUrl" alt="验证码" @click="getCode()" />
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit" :loading="saveLoading">
                    提交
                </van-button>
            </div>
        </van-form>
    </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import { Toast } from 'vant';
import Api from '@/api/homePage'
import { useRouter } from 'vue-router';
import userStore from '@/store/index.js';
const store = userStore()
const router = useRouter();

const userName = ref('admin');
const password = ref('123456');
const code = ref('');
const uuid = ref('');
const codeUrl = ref('');
onMounted(() => {
    getCode()
})

const saveLoading = ref(false);

const getCode = () => {
    Api.getCaptcha().then(res => {
        codeUrl.value = "data:image/gif;base64," + res.data.img;
        uuid.value = res.data.uuid;
    })
}

const onSubmit = (values) => {
    if (!userName.value || !password.value || !code.value) {
        return false
    }
    saveLoading.value = true
    Api.login({
        userName: userName.value,
        password: password.value,
        code: code.value,
        uuid: uuid.value,
        isMobile: 1
    }).then(res => {
        localStorage.setItem('token', res.data.token)
        Toast.success('登录成功');
        Api.getInfo().then(res => {
            localStorage.setItem('userId', res.data.sysUser.id)
            router.push('/home')
        })
    }).finally(() => {
        saveLoading.value = false
    })
};
</script>

<style lang="scss" scoped>
.container {
    background-color: #f7f8fa;
    padding: 10px;
    height: 100vh;

    h1 {
        font-size: 20px;
        font-weight: bold;
    }

    .logo {
        width: 100px;
        text-align: center;
        margin: 40px auto;

        img {
            width: 100%;
        }
    }
}
</style>